package com.mrs.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mrs.common.Result;
import com.mrs.entity.Files;
import com.mrs.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * description: FileController
 * date: 2022/7/19 17:55
 * author: MR.孙
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.upload.path}")
    private String filepath;

    @Autowired
    private FileMapper fileMapper;

    //文件上传
    @PostMapping("/upload")
    public String fileLoad(MultipartFile file) throws IOException {
        //获取文件名
        String filename = file.getOriginalFilename();
        //获取文件类型
        String fileType = FileUtil.extName(filename);
        //获取文件大小
        long fileSize = file.getSize();



        File uploadFile = new File(filepath);
        //判断配置文件的目录是否存在，若不存在则创建一个新的文件目录
        if(!uploadFile.exists()){
            uploadFile.mkdirs();
        }

        //定义一个文件唯一的标时码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID=uuid+ StrUtil.DOT+fileType;

        File uploadfile = new File(filepath + fileUUID);



        //获取文件的url
        String url;
        //获取上传文件的md5
        String md5 = SecureUtil.md5(file.getInputStream());
        //从数据库查询是否存在相同的记录
        Files fileMd5 = getFileByMd5(md5);
        if(fileMd5!=null){//文件已存在
            url=fileMd5.getUrl();

        }else{
            //写入到磁盘
            file.transferTo(uploadfile);
            url="http://localhost:8888/file/"+fileUUID;
        }


        Files files = new Files();
        files.setName(fileUUID);
        files.setSize(fileSize/1024);
        files.setType(fileType);
        files.setUrl(url);
        files.setMd5(md5);

        //存到数据库
        fileMapper.insert(files);

        return url;

    }

    //文件下载
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识码获取文件
        File uploadfile = new File(filepath + fileUUID);

        //设置输出流的格式
        ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        outputStream.write(FileUtil.readBytes(uploadfile));
        outputStream.flush();
        outputStream.close();
    }

    //通过文件的md5查询文件
    public Files getFileByMd5(String md5){
        //查询文件的md5是否存在(根据md5判断是否为同一个文件)
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);

    }




    @PostMapping("/update")
    public Result update(@RequestBody Files files) {
        return Result.success(fileMapper.updateById(files));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(true);
        fileMapper.updateById(files);
        return Result.success("");
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        // select * from sys_file where id in (id,id,id...)
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<Files> files = fileMapper.selectList(queryWrapper);
        for (Files file : files) {
            file.setIsDelete(true);
            fileMapper.updateById(file);
        }
        return Result.success("");
    }

    /**
     * 分页查询接口
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        // 查询未删除的记录
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return Result.success(fileMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper));
    }


}


